package com.lnj.community.controller;

import com.lnj.community.annotation.LoginRequired;
import com.lnj.community.dao.entity.Event;
import com.lnj.community.dao.entity.User;
import com.lnj.community.event.EventProduct;
import com.lnj.community.service.LikeService;
import com.lnj.community.utiles.CommunityUtil;
import com.lnj.community.utiles.HostHolder;
import com.lnj.community.utiles.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

import static com.lnj.community.utiles.CommunityConstant.ENTITY_TYPE_POST;
import static com.lnj.community.utiles.CommunityConstant.TOPIC_LIKE;

@Controller
public class LikeController {
    @Autowired
    private LikeService likeService;
    @Autowired
    private EventProduct eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;

    @LoginRequired
    @RequestMapping(path = "/like", method = RequestMethod.POST)
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId,int postId) {
        User user = HostHolder.getUser();
        if (user == null) {
            return CommunityUtil.getJSONString(999, "请先登录");
        }

        // 点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);
        // 查询点赞数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 查询点赞状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        // 返回结果
        Map<String,Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        // 触发点赞事件
        if (likeStatus == 1) {
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(HostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    //点赞的帖子id
                    .setData("postId", postId);
            eventProducer.fireEvent(event);
        }

        //如果点赞的是帖子
        if(entityType==ENTITY_TYPE_POST){
            //计算帖子分数 先把帖子的id存到Redis中 然后在定时任务中计算分数
            String redisKey= RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey,postId);
        }


        return CommunityUtil.getJSONString(0, null, map);
    }

}
